package edu.study.common.util.file;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class HandleFileUtils {

    /**
     * 读取文件指定行数据
     *
     * @param fileAbsolutePath 文件路径
     * @param cutOff           分隔符
     * @param targetNo         指定读取一行数据，从第0行开始计数
     * @param encoding         编码方式
     * @return
     */
    public static String[] readFileOfTargetLine(String fileAbsolutePath, String cutOff, int targetNo, String encoding) {
        log.info("begin -读取文件指定行; the file path:{}, ", fileAbsolutePath);
        String[] strArray = new String[]{};
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader bfr = null;
        try {
            fis = new FileInputStream(new File(fileAbsolutePath));
            isr = new InputStreamReader(fis, encoding);
            bfr = new BufferedReader(isr);
            String lineTxt = null; // 每一行数据
            int i = 0;
            while ((lineTxt = bfr.readLine()) != null) {
                if (StringUtils.isBlank(lineTxt)) {
                    continue;
                }
                if (i == targetNo) {
                    strArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(lineTxt, cutOff);
                    break;
                }
                i++;
            }
        } catch (IOException e) {
            log.error("error - 读取文件指定行; the file path:{}", fileAbsolutePath, e);
        } finally {
            if (bfr != null) {
                try {
                    bfr.close();
                } catch (IOException e) {
                    log.error("读取文件指定行; bfr.close() Exception", e);
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    log.error("读取文件指定行; isr.close() Exception", e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error("读取文件指定行; fis.close() Exception", e);
                }
            }
        }
        log.info("end - 读取文件指定行; the file path:{}", fileAbsolutePath);
        return strArray;
    }

    /**
     * 从第N行开始读取文件内容，一直读到尾
     *
     * @param fileAbsolutePath 文件路径
     * @param cutOff           分隔符
     * @param begin            从第几行开始读取，从第0行开始计数
     * @param encoding         编码方式
     * @return 返回文件所有内容的List
     */
    public static List<String[]> readFileToEnd(String fileAbsolutePath, String cutOff, int begin, String encoding) {
        log.info("begin - HandleFileUtils.readFileAll(); the file path:{}", fileAbsolutePath);
        List<String[]> dataArrList = new ArrayList<String[]>(); // 返回list
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader bfr = null;
        try {
            fis = new FileInputStream(new File(fileAbsolutePath));
            isr = new InputStreamReader(fis, encoding);
            bfr = new BufferedReader(isr);
            String line = ""; // 每一行数据
            int i = 0;
            while ((line = bfr.readLine()) != null && StringUtils.isNotBlank(line)) {
                if (i >= begin) {
                    String[] srcTxt = StringUtils.splitByWholeSeparatorPreserveAllTokens(line, cutOff);
                    dataArrList.add(srcTxt);
                }
                i++;
            }
        } catch (IOException e) {
            log.error("error - HandleFileUtils.readFileAll(); the file path:{}", fileAbsolutePath, e);
            dataArrList = null;
        } finally {
            if (bfr != null) {
                try {
                    bfr.close();
                } catch (IOException e) {
                    log.error("HandleFileUtils.readFileAll(); bfr.close() Exception", e);
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    log.error("HandleFileUtils.readFileAll(); isr.close() Exception", e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error("HandleFileUtils.readFileAll(); fis.close() Exception", e);
                }
            }
        }
        log.info("end - HandleFileUtils.readFileAll(); the file path:{}", fileAbsolutePath);
        return dataArrList;
    }

    public static void writeFile(String fileAbsolutePath, List<String> lineList, String newline, String encoding) throws IOException {
        String writeFile = fileAbsolutePath;
        BufferedWriter bufferedWriter = null;
        try {
            FileTools.mkdirs(fileAbsolutePath);
            //创建一个空文件
            FileTools.touchFile(fileAbsolutePath);
            if(CollectionUtils.isEmpty(lineList)) {
            	log.info("已生成空文件[{}]", fileAbsolutePath);
            	return ;
            }
            FileOutputStream fileOutputStream = new FileOutputStream(writeFile);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, encoding);
            bufferedWriter = new BufferedWriter(outputStreamWriter);
            for (String line : lineList) {
                bufferedWriter.write(line + newline);
            }
            bufferedWriter.flush();
        } catch (IOException e) {
            log.error("输出文件发生异常 ", e);
            throw e;
        } finally {
            IOUtils.closeQuietly(bufferedWriter);
        }

    }

}
